package cz.af.portletExams.userExamsOverview;

import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.model.User;
import com.liferay.portal.service.UserLocalService;
import com.liferay.portal.service.UserLocalServiceUtil;
import cz.af.portletExams.backend.ExamsOverViewBackend;
import cz.af.portletExams.exapando.ExamsExpandoUtil;
import cz.af.portletExams.model.Exam;
import cz.af.portletExams.model.ExamOverviewUser;
import cz.af.portletExams.model.Subject;
import cz.af.portletExams.userExamsOverview.dto.DtoCreator;
import cz.af.portletExams.userExamsOverview.dto.SubjectForUserExamsView;
import cz.af.portletExams.util.AFPortletUtil;
import cz.af.portletExams.util.SessionConstants;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletSession;
import javax.portlet.RenderRequest;
import javax.xml.namespace.QName;
import java.util.List;

@Controller
@RequestMapping(value = "VIEW")
public class UserViewController {

    private static final Logger log = Logger.getLogger(UserViewController.class);

    @Autowired
    private ExamsOverViewBackend backend;

    @Autowired
    private ResourceBundleMessageSource messages;

    @RequestMapping
    public String renderDefault(Model model, PortletSession portletSession, RenderRequest renderRequest) throws SystemException, PortalException {
        ExamOverviewUser user = (ExamOverviewUser) portletSession.getAttribute(SessionConstants.USER, PortletSession.APPLICATION_SCOPE);
        if (user == null) {
            final String remoteUser = renderRequest.getRemoteUser();
            log.info("remoteUser " + remoteUser);
            if (remoteUser == null) {
                model.addAttribute(Validation.KOS_USERNAME_FORM, portletSession.getAttribute(Validation.KOS_USERNAME_FORM));
                return "userExamsOverview/viewForUsername";
            } else {
                final UserLocalService userLocalService = UserLocalServiceUtil.getService();
                final User userById = userLocalService.getUserById(Long.parseLong(remoteUser));
                log.info("userById email " + userById.getEmailAddress());
                final String usernameForUser = ExamsExpandoUtil.getUsernameForUser(Long.parseLong(remoteUser));
                if (usernameForUser != null && !usernameForUser.isEmpty()) {
                    user = new ExamOverviewUser(usernameForUser);
                    portletSession.setAttribute(SessionConstants.USER, user, PortletSession.APPLICATION_SCOPE);
                }
            }
        }

        if (user == null) {
            log.info("render default without user");
            model.addAttribute(Validation.KOS_USERNAME_FORM, portletSession.getAttribute(Validation.KOS_USERNAME_FORM));
            return "userExamsOverview/viewForUsername";
        }

        return handleForUserName(model, user);
    }

    private String handleForUserName(Model model, ExamOverviewUser user) {
        final String username = user.getUsername();
        log.info("render default " + username);
        final List<Subject> subjectsForUsername = backend.findSubjectsForUsername(username);
        final List<Exam> examsForUser = backend.findExamsForUser(username);
        final List<SubjectForUserExamsView> subjects = DtoCreator.createDtos(subjectsForUsername, examsForUser, user, backend);
        model.addAttribute("subjects", subjects);
        model.addAttribute("username", username);
        return "userExamsOverview/viewUserDetail";
    }


    @RequestMapping(params = "action=username_set_action")
    public void setUserName(@RequestParam(value = "username") String username, PortletSession portletSession,
                            ActionRequest actionRequest, ActionResponse actionResponse) {
        log.info("username_set_action " + username);
        final boolean usernameValid = backend.isUsernameValid(username);
        if (usernameValid) {
            portletSession.removeAttribute(Validation.KOS_USERNAME_FORM);
            final ExamOverviewUser user = new ExamOverviewUser(username);
            portletSession.setAttribute(SessionConstants.USER, user, PortletSession.APPLICATION_SCOPE);
            final String remoteUser = actionRequest.getRemoteUser();
            if (remoteUser != null) {
                ExamsExpandoUtil.setUsernameForUser(Long.parseLong(remoteUser), username);
            }
            AFPortletUtil.redirectToRoot(actionResponse, actionRequest);
        } else {
            portletSession.setAttribute(Validation.KOS_USERNAME_FORM,
                    messages.getMessage("validation.username.notexist", new Object[]{}, actionRequest.getLocale()));
        }
    }

    @RequestMapping(params = "action=username_unset_action")
    public void unsetUserName(ActionRequest actionRequest, ActionResponse actionResponse, PortletSession portletSession) {
        log.info("username_unset_action ");
        portletSession.removeAttribute(SessionConstants.USER, PortletSession.APPLICATION_SCOPE);
        final String remoteUser = actionRequest.getRemoteUser();
        if (remoteUser != null) {
            ExamsExpandoUtil.setUsernameForUser(Long.parseLong(remoteUser), null);
        }
        AFPortletUtil.redirectToRoot(actionResponse, actionRequest);
    }


    @RequestMapping(params = "action=showSubjectDetail")
    private void showSubjectDetailInOtherPortlet(ActionResponse actionResponse, ActionRequest actionRequest, @RequestParam(required = true) String subjectId) {
        log.info("showSubjectDetailInOtherPortlet " + subjectId);
        QName eventName = new QName("http://fiserale/events", "subject.id");
        actionResponse.setEvent(eventName, subjectId);
        AFPortletUtil.redirectToRoot(actionResponse, actionRequest);
    }

}